﻿using MCUPackage.DesignEditor;
using MCUPackage.Utils;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;

namespace SxPackages.STC32G.Models
{
	/// <summary>
	/// 看门狗配置
	/// </summary>
	[Serializable]
	class WDGOptions
	{
		protected STC32GQFP64 mParent = null;

		/// <summary>
		/// 使能看门狗
		/// </summary>
		[DisplayName("启用看门狗"),
		DefaultValue(false),
		JsonProperty(Order = 100),
		Description("是否启用系统看门狗")]
		public bool Enable { get; set; } = false;
		/// <summary>
		/// IDLE模式下继续计数
		/// </summary>
		[DisplayName("IDLE模式控制"),
		DefaultValue(false),
		Description("在IDLE模式下是否启用系统看门狗")]
		public bool EnableIdle { get; set; } = false;

		private int mPS = 64;
		/// <summary>
		/// 分频系数
		/// </summary>
		[DisplayName("分频系数"),
		DefaultValue(64),
		TypeConverter(typeof(IntCollectionConvertor)),
		IntCollection(new int[] { 2, 4, 8, 16, 32, 64, 128, 256 }),
		Description("分频系数越大看门狗溢出时间越长")]
		public int PS
		{
			get => mPS;
			set
			{
				if (mPS != value)
				{
					mPS = value;
					// 计算溢出时间
					double ms = GetOverflowTime();
					if (ms > 1000)
					{
						mParent.UpdateMsg(string.Format("看门狗溢出时间{0:F2}秒", ms / 1000));
					}
					else
					{
						mParent.UpdateMsg(string.Format("看门狗溢出时间{0:F2}毫秒", ms));
					}
				}
			}
		}

		/// <summary>
		/// 获取溢出时间, 单位ms
		/// </summary>
		/// <returns></returns>
		private double GetOverflowTime()
		{
			double result = 12 * 32768 * mPS;
			// 除以MHz得出的是us数, 除以KHz得出的为ms数
			return result / (mParent.mSYSTEM.FreqValue);
		}

		public WDGOptions(STC32GQFP64 aParent)
		{
			this.mParent = aParent;
		}

		public override string ToString()
		{
			return string.Empty;
		}

		/// <summary>
		/// 初始化模板
		/// </summary>
		private const string TEMPLATE =
@"	attr.WDT_Enable     = ENABLE;			//看门狗使能   ENABLE或DISABLE
	attr.WDT_IDLE_Mode  = {0};	//IDLE模式是否停止计数		WDT_IDLE_STOP,WDT_IDLE_RUN
	// {1}
	attr.WDT_PS         = WDT_SCALE_{2};	//看门狗定时器时钟分频系数	WDT_SCALE_2,WDT_SCALE_4,WDT_SCALE_8,WDT_SCALE_16,WDT_SCALE_32,WDT_SCALE_64,WDT_SCALE_128,WDT_SCALE_256
	WDT_Inilize(&attr);					//初始化";

		public bool AppendConfig(List<string[]> aLst)
		{
			if (!this.Enable)
			{
				return false;
			}

			string name = "WDT_Config";
			StringBuilder tmpSb = new StringBuilder();
			tmpSb.Append(TemplateHelper.GetFunctionCommit("看门狗模块初始化"));
			tmpSb.AppendLine($"PRIVATE void {name}(void)").AppendLine("{");
			tmpSb.AppendLine("\tWDT_InitTypeDef attr;");
			tmpSb.AppendLine();
			double ms = GetOverflowTime();
			string str = string.Empty;
			if (ms > 1000)
			{
				str = string.Format("看门狗溢出时间{0:F2}秒", ms / 1000);
			}
			else
			{
				str = string.Format("看门狗溢出时间{0:F2}毫秒", ms);
			}
			tmpSb.AppendFormat(TEMPLATE, this.EnableIdle ? "WDT_IDLE_RUN" : "WDT_IDLE_STOP", str, this.PS);
			tmpSb.AppendLine();
			tmpSb.AppendLine("}");
			aLst.Add(new string[] { tmpSb.ToString(), $"{name}();" });

			return true;
		}
	}
}